<template>
  <div class="app-container">
    <el-form
      class="searchform"
      @submit.native.prevent
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="签章名称">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <div class="tableoperation">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          plain
          @click="openDialog()"
          >新增</el-button
        >
      </div>

      <el-table
        v-loading="loading"
        :height="height - 400 + 'px'"
        :data="dataList"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column label="签章图片" align="center">
          <template slot-scope="{ row }">
            <img :src="row.url" style="max-width: 100px" />
            <!-- <el-image
						style="width: 100px; height: 100px"
						:preview-src-list="[row.url]"
						:src="row.url">
					</el-image> -->
          </template>
        </el-table-column>
        <el-table-column label="签章名称" align="center" prop="name" />
        <el-table-column label="印章环绕文字" align="center" prop="surround" />
        <el-table-column label="副文" align="center" prop="subheading" />
        <el-table-column label="防伪文字" align="center" prop="security" />
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.type != 0"
              @click.native.prevent="openDialog(row)"
              type="text"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="handleDelete(row)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="addDialog"
      width="900px"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :disabled="status == '3'"
        ref="form"
        :rules="rules"
        size="small"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="印章名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="印章环绕文字" prop="surround">
              <el-input
                v-model="form.surround"
                placeholder="请输入"
                @blur="generator"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="副文">
              <el-input
                v-model="form.subheading"
                placeholder="请输入"
                @blur="generator"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="防伪文字">
              <el-input
                v-model="form.security"
                placeholder="请输入"
                @blur="generator"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="印章类型" prop="type">
              <el-select
                v-model="form.type"
                style="width: 100%"
                :disabled="status != '1'"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in sealTypeList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="印章形状" prop="shape">
              <el-select
                v-model="form.shape"
                style="width: 100%"
                @change="changeShape"
                disabled
              >
                <el-option
                  v-for="dict in dict.type.seal_shape"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签章" class="star">
              <!-- <div class="imgcontainer">
								<div class="avatar-container"> -->
              <!-- <img v-if="imageUrlT" :src="imageUrlT"> -->
              <!-- <img v-else :src="blankImg"> -->
              <el-upload
                class="avatar-uploader"
                :action="upload.url"
                :headers="upload.headers"
                :show-file-list="false"
                :on-success="handleFileSuccessThird"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrlT" :src="imageUrlT" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <!-- </div>
							</div> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" v-if="status != '3'" @click="submitForm"
          >确 定</el-button
        >
        <el-button v-if="status != '3'" @click="dialogVisible = false"
          >取 消</el-button
        >
        <el-button v-if="status == '3'" @click="dialogVisible = false"
          >关 闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
} from "@/api/system/user";
import {
  equipmentTypeList,
  equipmentTypeExport,
  equipmentTypeDetail,
  equipmentTypeAdd,
  equipmentTypeEdit,
  equipmentTypeDelete,
} from "@/api/basicData/equipmentType";
import {
  sealList,
  getInfoSeal,
  sealAdd,
  sealUpdate,
  sealRemove,
  generator,
  upload,
} from "@/api/basicData/seal";
import { listOss, listByIds, delOss } from "@/api/system/oss";
import { getToken } from "@/utils/auth";
import blankImg from "@/assets/images/img.jpg";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "seal",
  dicts: ["seal_shape", "seal_type"],
  data() {
    return {
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "印章名称不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "印章类型不能为空", trigger: "blur" },
        ],
        surround: [
          { required: true, message: "印章环绕文字不能为空", trigger: "blur" },
        ],
        shape: [
          { required: true, message: "印章形状不能为空", trigger: "blur" },
        ],
        subheading: [
          { required: true, message: "副文不能为空", trigger: "blur" },
        ],
        security: [
          { required: true, message: "防伪文字不能为空", trigger: "blur" },
        ],
        // ossId: [
        //   { required: true, message: "签章不能为空", trigger: "blur" },
        // ],
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Disposition": "inline",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      },
      imageUrlT: "",
      blankImg: blankImg,
      // 印章列表
      dataList: [],
      total: 0,
      dialogVisible: false,
      status: "",
      title: "",
      sealTypeList: [],
    };
  },
  created() {
    // 	 // WebSocet 通信模型

    // // 1. 拨打电话（建立连接）
    // // 注意：wss://echo.websocket.org 是一个在线的测试接口，仅用于 WebSocket 协议通信测试使用
    // var ws = new WebSocket("wss://echo.websocket.org");

    // // 当连接建立成功，触发 open 事件
    // ws.onopen = function(evt) {
    //   console.log("建立连接成功 ...");

    //   // 连接建立成功以后，就可以使用这个连接对象通信了
    //   // send 方法发送数据
    //   ws.send("Hello WebSockets!");
    // };

    // // 当接收到对方发送的消息的时候，触发 message 事件
    // // 我们可以通过回调函数的 evt.data 获取对方发送的数据内容
    // ws.onmessage = function(evt) {
    //   console.log("接收到消息: " + evt.data);

    //   // 当不需要通信的时候，可以手动的关闭连接
    //   // ws.close();
    // };

    // // 当连接断开的时候触发 close 事件
    // ws.onclose = function(evt) {
    //   console.log("连接已关闭.");
    // }
    this.getList();
    getDicts("seal_type").then((response) => {
      // this.sealTypeList = response.data;
      this.sealTypeList = response.data.filter((item) => {
        return item.dictLabel != "私章";
      });
    });
  },
  methods: {
    // 获取印章列表
    getList() {
      this.loading = true;
      sealList(this.queryParams)
        .then((response) => {
          this.dataList = response.rows;
          this.dataList.forEach((item) => {
            // 根据ossId查询图片url
            if (item.ossId) {
              listByIds(item.ossId).then((response) => {
                this.$set(
                  item,
                  "url",
                  response.data[0] && response.data[0].url
                );
                // item.url = response.data[0] && response.data[0].url;
              });
            }
          });

          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 更改形状
    changeShape(val) {
      console.log("更改形状", val);
      this.generator();
    },
    // 构建印章
    generator() {
      console.log("失焦");
      if (!this.form.surround) {
        // this.$modal.msgWarning("请输入印章环绕文字！");
        // this.$modal.msgError(`请输入印章环绕文字！`);
        // this.$modal
        // .confirm('请输入印章环绕文字！')
        // .then(() => {
        // })
        // .finally(() => {
        // });
        // return;
      }
      generator({
        surround: this.form.surround,
        subheading: this.form.subheading,
        security: this.form.security,
        type: this.form.shape,
      }).then((response) => {
        if (response.msg) {
          this.imageUrlT = "data:image/png;base64," + response.msg;
        }
      });
    },
    // 打开对话框
    openDialog(row, status) {
      if (row && row.type == "0") return; /* 私章 */
      this.resetForm("form");
      this.form = {};
      this.imageUrlT = "";
      if (row) {
        if (status) {
          this.status = "3";
          this.title = "查看印章";
        } else {
          this.status = "2";
          this.title = "编辑印章";
        }
        getInfoSeal(row.id).then((response) => {
          this.form = response.data;
          this.form.shape = String(this.form.shape || "");
          this.form.type = String(this.form.type || "");
          if (this.form.ossId) {
            listByIds(this.form.ossId).then((response) => {
              this.imageUrlT = response.data[0] && response.data[0].url;
            });
          }
          this.dialogVisible = true;
        });
      } else {
        this.status = "1";
        this.title = "添加印章";
        this.$set(this.form, "type", "1");
        this.$set(this.form, "shape", "1");
        this.dialogVisible = true;
      }
    },
    // 将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    // 再将blob转换为file
    blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
      theBlob.name = fileName; // 文件名
      return new File([theBlob], fileName, {
        type: theBlob.type,
        lastModified: Date.now(),
      });
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.imageUrlT) {
            this.$modal.msgWarning("签章不能为空！");
            return;
          }
          console.log(
            "this.imageUrlT",
            this.imageUrlT,
            this.imageUrlT.indexOf("base64")
          );

          // 如果图片是base64格式则要上传获得ossId 否则直接取form里的ossId
          if (this.imageUrlT.indexOf("base64") != -1) {
            let base64 = this.imageUrlT;
            let blob = this.dataURLtoBlob(base64);
            console.log("blob", blob);
            // 拿到文件名
            let fileName = this.form.name;
            // 2，在转为 file类型
            let file1 = this.blobToFile(blob, fileName);
            console.log("file1:", file1);

            let fd = new FormData();
            fd.append("file", file1);
            upload(fd).then((response) => {
              console.log("成功", response);
              // this.form.ossId = response.data.ossId;
              this.$set(this.form, "ossId", response.data.ossId);
              this.submit();
            });
          } else {
            this.submit();
          }
        }
      });
    },
    submit() {
      if (this.status == "1") {
        sealAdd(this.form).then((response) => {
          this.$modal.msgSuccess("添加成功");
          this.dialogVisible = false;
          this.getList();
        });
      }
      if (this.status == "2") {
        sealUpdate(this.form).then((response) => {
          this.$modal.msgSuccess("编辑成功");
          this.dialogVisible = false;
          this.getList();
        });
      }
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除该印章？")
        .then(() => {
          this.loading = true;
          return sealRemove(row.id);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 查询重置
    reset() {
      (this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }),
        this.resetForm("queryParams");
      this.getList();
    },
    // 文件上传成功处理
    handleFileSuccessThird(response, file, fileList) {
      console.log("response, file", response, file);
      if (response.data) {
        this.imageUrlT = URL.createObjectURL(file.raw);
        this.$set(this.form, "ossId", response.data.ossId);
        // this.form.ossId = response.data.ossId;
      }
    },
    // 上传格式验证
    beforeAvatarUpload(file) {
      console.log("上传格式验证", file, file.type.match(/(\S*)\//)[1]);
      let suffix = file.type.match(/(\S*)\//)[1];

      if (suffix != "image") {
        this.$message.warning("请上传图片格式!");
        return false;
      }
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .addDialog {
  .el-form {
    margin-left: -30px;
  }
}
::v-deep .star .el-form-item__label::before {
  content: "* ";
  color: red;
}
// .imgcontainer {
// 	height: 170px;
// 	// background: rgba(0, 0, 255, 0.185);
// 	.avatar-container {
// 		width: 150px;
// 		// background: rgba(255, 0, 0, 0.096);
// 		border: 1px solid #cfcfcf;
// 		margin-top: 20px;
// 		padding: 2px;
// 		img {
// 			display: block; /* 底部空白间隙 */
// 			width: 100%;
// 		}
// 	}
// }

::v-deep .avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  // border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  padding: 3px;

  // border: 1px solid #999 !important;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
